import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class Client {

    private String path = "C:\\Users\\humble\\projectCenter\\NIO_demo\\src\\files";

    ByteBuffer buffer = ByteBuffer.allocate(BufferConfig.BUFFER_SIZE);

    private Charset charset = StandardCharsets.UTF_8;

    private static final Logger logger = Logger.getLogger(Client.class.getName());

    SocketChannel socketChannel;

    public Client(int port) throws IOException {
        socketChannel = SocketChannel.open();
        socketChannel.bind(new InetSocketAddress(port));
        boolean connect = socketChannel.connect(new InetSocketAddress("127.0.0.1", 12345));
        logger.info(port+"client Connected to " + socketChannel.getRemoteAddress());
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client(10001);
        client.uploadFile("美图.jpg",client.socketChannel);
    }
    public void uploadFile(String fileName,SocketChannel socketChannel) throws IOException {
        buffer.clear();
        byte[] bytes = fileName.getBytes(charset);
        buffer.putInt(bytes.length);
        buffer.put(bytes);

        File file = new File(path + File.separator + fileName);
        if(!file.exists()){
            logger.warning("File does not exist");
        }
        long fileLength = file.length();

        buffer.putLong(fileLength);
        buffer.flip();
        socketChannel.write(buffer);
        buffer.clear();
        FileChannel fileChannel = new FileInputStream(file).getChannel();
        int readLength = 0;
        while((readLength = fileChannel.read(buffer)) > 0) {
            buffer.flip();

            socketChannel.write(buffer);
            buffer.clear();
        }
        logger.info("文件传输完毕!");
        fileChannel.close();
    }
}
